package com.epro.dx.activity.currency;

import java.util.ArrayList;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.util.AsyncTaskUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.EventBuilder;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.CurrencyModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.StringUtil;

/**
 * @author Tony
 * 多货币展示列表页面
 */
public class CurrencyActivity extends BaseFragmentActivity {
	
	private ListView curencyListView;
	private CurrencyListAdapter currencyListAdapter;
	
	//支持支付的币种
	private ArrayList<CurrencyModel> currencyModelList_canPay = new ArrayList<CurrencyModel>();
		
	//仅支持显示的币种
	private ArrayList<CurrencyModel> currencyModelList_showOnly = new ArrayList<CurrencyModel>();
	private Tracker tracker;
	private EventBuilder eventBuilder;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		tracker = DXApplication.getContext().getTracker(TrackerName.APP_TRACKER);
		tracker.setScreenName("CurrencyList");
		tracker.send(new HitBuilders.ScreenViewBuilder().build());
		eventBuilder = new HitBuilders.EventBuilder();
		initView();
		initData();
		initEvent();
	}

	/**
	 * 数据过滤分类
	 */
	private void filtData(ArrayList<CurrencyModel> currencyModelList) {
		if(currencyModelList!=null&&currencyModelList.size()>0){
			currencyModelList_canPay.clear();
			currencyModelList_showOnly.clear();
			
			String nowCurrencyCode = StringUtil.getConfig(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE, getString(R.string.currency_default_currencyCode));
			
			//分为可以支付与仅可以显示两类
			for(int i = 0;i<currencyModelList.size();i++){
				CurrencyModel model = currencyModelList.get(i);
				if(nowCurrencyCode.equals(model.getCurrencyCode())){
					model.setChecked(true);
				}else{
					model.setChecked(false);
				}
				if(model.isCanPay()){
					currencyModelList_canPay.add(model);
				}else{
					currencyModelList_showOnly.add(model);
				}
			}
		}
		
	}
	
	private void initEvent() {
		curencyListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 点击某一个条目改变本地存储的CurrencyCode并刷新页面
				String currencyCode = null;
				String currencyCodeSymbol = null;
				if(currencyModelList_canPay.size()>0){//可支付的货币列表不为空
					if(position==0){//此处为提示信息
						return;
					}
					if(position<=currencyModelList_canPay.size()){
						currencyCode = currencyModelList_canPay.get(position-1).getCurrencyCode();
						currencyCodeSymbol = currencyModelList_canPay.get(position-1).getCurrencyCodeSymbol();
					}else{
						if(position==currencyModelList_canPay.size()+1){//此处为提示信息
							return;
						}
						currencyCode = currencyModelList_showOnly.get(position-currencyModelList_canPay.size()-2).getCurrencyCode();
						currencyCodeSymbol = currencyModelList_showOnly.get(position-currencyModelList_canPay.size()-2).getCurrencyCodeSymbol();
					}
				}else {//可支付列表为空
					if(position == 0){//此处为提示信息
						return;
					}
					currencyCode = currencyModelList_showOnly.get(position-1).getCurrencyCode();
					currencyCodeSymbol = currencyModelList_showOnly.get(position-currencyModelList_canPay.size()-2).getCurrencyCodeSymbol();
				}
				if(!TextUtils.isEmpty(currencyCode)){
					eventBuilder.setCategory("Choose Currency").setAction(currencyCode);
					tracker.send(eventBuilder.build());
				}
				//加标记，回到主页时刷新推荐产品列表信息
				StringUtil.saveConfig("Home_RefreshBFD", "true");
				StringUtil.saveConfig(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE,currencyCode );//保存货币简写
				StringUtil.saveConfig(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE_SYMBOL,currencyCodeSymbol );//保存货币符号
//				AsyncTaskUtil.executeTask(new GetCurrencyListTask());
				String nowCurrencyCode = StringUtil.getConfig(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE, getString(R.string.currency_default_currencyCode));
				for(int i = 0;i<currencyModelList_canPay.size();i++){
					if(nowCurrencyCode.equals(currencyModelList_canPay.get(i).getCurrencyCode())){
						currencyModelList_canPay.get(i).setChecked(true);
					}else{
						currencyModelList_canPay.get(i).setChecked(false);
					}
				}
				for(int i = 0;i<currencyModelList_showOnly.size();i++){
					if(nowCurrencyCode.equals(currencyModelList_showOnly.get(i).getCurrencyCode())){
						currencyModelList_showOnly.get(i).setChecked(true);
					}else{
						currencyModelList_showOnly.get(i).setChecked(false);
					}
				}
				currencyListAdapter.notifyDataSetChanged();
				finish();
			}
		});
		
		//网络错误页面重试按钮的点击事件
		retryBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 尝试请求接口刷新数据
				AsyncTaskUtil.executeTask(new GetCurrencyListTask());
			}
		});
	}

	private void initData() {
		currencyListAdapter = new CurrencyListAdapter(getApplicationContext(),currencyModelList_canPay,currencyModelList_showOnly);
		curencyListView.setAdapter(currencyListAdapter);
		AsyncTaskUtil.executeTask(new GetCurrencyListTask());
	}

	private void initView() {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_currency);
		curencyListView = (ListView) findViewById(R.id.currency_list);
		setLeftBtnContent(true, -1);
		setTitleContent(R.string.currency_title);
	}
	
	/**
	 * @author tony
	 * 获取货币列表的任务
	 */
	public class GetCurrencyListTask extends AsyncTask<Void, Void, String>{

		ArrayList<CurrencyModel> currencyCodes = null;
		@Override
		protected void onPreExecute() {
//			showWaitingDialog();
			showLoadingLayout(curencyListView);
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(Void... params) {
			try {
				currencyCodes = ProviderFactory.createCurrencyServiceProvider().getCurrencyCodes();
			} catch (DxException e) {
				return e.getErrCode();
			}
			return "0";
		}
		@Override
		protected void onPostExecute(String result) {
			if("0".equals(result)){
				hideAllLayout(curencyListView);
				if(currencyCodes!=null){
					filtData(currencyCodes);
					currencyListAdapter.notifyDataSetChanged();
				}
			}else{
				//错误提示处理
				if(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)){
					showErrorLayout(curencyListView, R.string.internet_error,
							R.string.internet_suggest, R.drawable.no_internet);
				}else{
					showErrorLayout(curencyListView, R.string.server_busy,
							R.string.server_suggest, R.drawable.no_internet);
				}
			}
			super.onPostExecute(result);
		}
		
	}
}
